﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Publishing;

using CSP.Core;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.Win32;
using System.Web.UI.WebControls.WebParts;

namespace CSP.Receivers
{
    public class CrmConnectorFeatureReceiver : SPFeatureReceiver
    {

        private string SubstituteNull(object o)
        {

            if (o == null)

                return String.Empty;

            else

                return o.ToString();

        }

        private string DefaultEndPointAddress
        {
            get
            {
                return RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "WCFEndPointURL");
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {



            // feature is scoped at Web, so the parent is type SPWeb rather than SPSite..
            using (SPWeb web = properties.Feature.Parent as SPWeb)
            {

                List<ModificationEntry> modifications = new List<ModificationEntry>();
                modifications.Add(new ModificationEntry("address", "configuration/system.serviceModel/client/endpoint", DefaultEndPointAddress));

                foreach (ModificationEntry entry in modifications)
                {
                    web.Site.WebApplication.WebConfigModifications.Add(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute)
                    );
                }


                PublishingWeb pweb = PublishingWeb.GetPublishingWeb(web);
                foreach (PublishingPage page in pweb.GetPublishingPages())
                {
                    SPFile file = page.ListItem.File;
                    if (file.Name == "default.aspx")
                    {
                        page.CheckOut();
                        SPLimitedWebPartCollection webparts = file.GetLimitedWebPartManager(PersonalizationScope.Shared).WebParts;

                        Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared);


                        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
                        {
                            if (wp.Title == "My cases")
                            {
                                string crmUrl = RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmServerUrl");
                                string crmOrganization = RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, "CrmOrganizationName");
                                string url = string.Format( "{0}/{1}/cs/cases/edit.aspx",crmUrl, crmOrganization);
                                wp.WebBrowsableObject.GetType().GetMethod("set_OpenCaseInNewWindow").Invoke(wp, new object[] { true });
                                wp.WebBrowsableObject.GetType().GetMethod("set_CaseDetailsURL").Invoke(wp, new object[] { url });
                                mgr.SaveChanges(wp);
                                break;
                            }
                        }
                        page.Update();
                        page.CheckIn(string.Empty);
                        file.Publish(string.Empty);
                        if (page.ListItem.ParentList.EnableModeration)
                        {
                            file.Approve(string.Empty);
                        }

                        break;
                    }
                }
            }
        }


        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // feature is scoped at Web, so the parent is type SPWeb rather than SPSite..
            using (SPWeb web = properties.Feature.Parent as SPWeb)
            {
                List<ModificationEntry> modifications = new List<ModificationEntry>();
                modifications.Add(new ModificationEntry("address", "configuration/system.serviceModel/client/endpoint", DefaultEndPointAddress));

                foreach (ModificationEntry entry in modifications)
                {
                    web.Site.WebApplication.WebConfigModifications.Add(ModificationEntryHelper.CreateModification(entry.Name, entry.XPath, entry.Value, SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute)
                    );
                }

                PublishingWeb pweb = PublishingWeb.GetPublishingWeb(web);
                foreach (PublishingPage page in pweb.GetPublishingPages())
                {
                    SPFile file = page.ListItem.File;
                    if (file.Name == "default.aspx")
                    {
                        page.CheckOut();
                        SPLimitedWebPartCollection webparts = file.GetLimitedWebPartManager(PersonalizationScope.Shared).WebParts;

                        Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared);


                        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
                        {
                            if (wp.Title == "My cases")
                            {
                                string url = web.Site.Url + "/Procedures/Pages/case_details.aspx";
                                wp.WebBrowsableObject.GetType().GetMethod("set_OpenCaseInNewWindow").Invoke(wp, new object[] { false });
                                wp.WebBrowsableObject.GetType().GetMethod("set_CaseDetailsURL").Invoke(wp, new object[] { url });
                                mgr.SaveChanges(wp);
                                break;
                            }
                        }
                        page.Update();
                        page.CheckIn(string.Empty);
                        file.Publish(string.Empty);
                        if (page.ListItem.ParentList.EnableModeration)
                        {
                            file.Approve(string.Empty);
                        }

                        break;
                    }
                }
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

    }
}
